<?php

namespace api\controller;

// +----------------------------------------------------------------------
// | 计划控制层
// +----------------------------------------------------------------------

use common\controller\VerifyController;
use common\exception\LogicException;
use common\service\ProjectService;
use common\service\ScheduleService;
use common\validate\Schedule;
use support\ErrorCode;
use think\Exception;
use think\Request;

class ScheduleController extends VerifyController
{
    private $scheduleService;

    public function __construct()
    {
        parent::__construct();
        $this->scheduleService = new ScheduleService();
    }

    /**
     * 集排期信息
     * @param Request $request
     * @return \think\Response|void
     * @throws Exception
     */
    public function getEpisodeSchedule(Request $request)
    {
        try {
            $res = $this->scheduleService->getEpisodeSchedule($request->param()['param']['filter']['project_id'], $request->getTenantId());
            return json($res);
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 集分类排期查询
     * @param Request $request
     * @return \think\Response|void
     * @throws Exception
     */
    public function getEpisodeStepCategorySchedule(Request $request)
    {
        try {
            $filter = $request->param()['param']['filter'];

            $res = $this->scheduleService->getEpisodeStepCategorySchedule($filter['project_id'], $filter['episode_id']);
            return json($res);
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 集分类实体任务排期查询
     * @param Request $request
     * @return \think\Response|void
     * @throws Exception
     */
    public function getEpisodeStepCategoryEntityTaskSchedule(Request $request)
    {
        try {
            $param = $request->param()['param'];
            $res = $this->scheduleService->getEpisodeStepCategoryEntityTaskSchedule($param);
            return json($res);
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 后台-排班管理列表
     * @param Request $request
     * @return \think\Response|void
     */
    public function getScheduleManageList(Request $request)
    {
        try {
            $param = $request->param()['param'];
            $startTime = $param['start_time'] ?? '';
            $endTime = $param['end_time'] ?? '';
            $list = $this->scheduleService->getScheduleManageList($param, $request->getTenantId());
            $rangeTime = get_month_day_list($startTime, $endTime);
            $listMap = [];
            foreach ($list ?? [] as $value) {
                $projectId = !empty($value['project_id']) ? $value['project_id'] : "#";
                $listMap[$projectId][$value['schedule_time']] = $value;
            }
            // 查询所有项目
            $projectList = ProjectService::getInstance()->getProjects(['tenant_id' => $request->getTenantId()], "id,name,'project' as type");
            array_unshift($projectList, ['id' => '#', 'name' => '默认排班', 'type' => 'default']);
            $returnData = [];
            foreach ($projectList as $projectItem) {
                $workdays = [];
                foreach ($rangeTime as $day) {
                    $dayTime = strtotime($day);
                    $workdays[] = [
                        'id' => $listMap[$projectItem['id']][$dayTime]['id'] ?? '-',
                        'date' => $day,
                        'is_work' => $listMap[$projectItem['id']][$dayTime]['is_work'] ?? 'default',
                        'week_type' => $listMap[$projectItem['id']][$dayTime]['week_type'] ?? '',
                    ];
                }
                $returnData[] = ['title' => $projectItem['name'], 'type' => $projectItem['type'], 'workdays' => $workdays,];
            }
            return json(success_response('', $returnData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 后台-创建排班管理
     * @param Request $request
     * @return \think\Response|void
     * @throws Exception
     */
    public function createScheduleManageData(Request $request)
    {
        try {
            $param = $request->param()['param'];
            $validate = new Schedule();
            foreach ($param['data'] as $item) {
                if (!$validate->check($item, null, 'CreateScheduleManageDataItem')) {
                    throw_strack_exception($validate->getError(), ErrorCode::CREATE_SCHEDULE_MANAGE_VALIDATE_FAIL);
                }
            }
            $res = $this->scheduleService->createScheduleManageData($param);
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 后台-排班管理列表获取单条
     * @param Request $request
     * @return \think\Response|void
     */
    public function getScheduleManageOne(Request $request)
    {
        try {
            $param = $request->param()['param'];
            $list = $this->scheduleService->getScheduleManageOne($param, $request->getTenantId());
            if (empty($list)) {
                return json(success_response('', []));
            }
            return json(success_response('', $list));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }
}
